import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { defineConfig, loadEnv } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { VantResolver } from '@vant/auto-import-resolver'

const pathResolve = (dir) => {
    return resolve(__dirname, '.', dir)
}

export default defineConfig((mode) => {
    const env = loadEnv(mode.mode, process.cwd())

    return {
        plugins: [
            vue(),
            AutoImport({
                resolvers: [VantResolver()],
            }),
            Components({
                resolvers: [VantResolver()],
            }),
        ],
        resolve: {
            alias: {
                '@': pathResolve('./src/'),
            },
        },
        base: mode.command === 'serve' ? './' : env.VITE_PUBLIC_PATH,
        server: {
            host: '0.0.0.0',
            port: Number(env.VITE_PORT),
            proxy: {
                '/dev-api': {
                    target: 'http://192.168.0.149:8808',
                    changeOrigin: true,
                    rewrite: (p) => p.replace(/^\/dev-api/, ''),
                },
            },
        },
        build: {
            outDir: 'dist',
            chunkSizeWarningLimit: 1500,
            rollupOptions: {
                output: {
                    chunkFileNames: 'assets/js/[name]-[hash].js',
                    entryFileNames: 'assets/js/[name]-[hash].js',
                    assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
                    manualChunks(id) {
                        if (id.includes('node_modules')) {
                            return (
                                id.toString().match(/\/node_modules\/(?!.pnpm)(?<moduleName>[^\/]*)\//)?.groups
                                    ?.moduleName ?? 'vender'
                            )
                        }
                    },
                },
            },
        },
    }
})
